<template>
  <div class="dept-manage">
    <div class="query-form">
      <el-form :inline="true" ref="queryFormRef" :model="queryForm">
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            placeholder="请输入部门名称"
            v-model="queryForm.deptName"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getDeptList">查询</el-button>
          <el-button @click="handleReset(queryFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="action">
        <el-button type="primary" @click="handleOpen" v-has="'dept-create'"
          >+创建</el-button
        >
      </div>
      <el-table
        :data="deptList"
        row-key="_id"
        :tree-props="{ children: 'children' }"
        stripe
      >
        <el-table-column v-for="item in columns" :key="item._id" v-bind="item">
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)"
              v-has="'dept-edit'"
              >编辑</el-button
            >
            <Modal
              title="确定要删除？"
              @handleDel="handleDel(scope.row._id)"
              v-has="'dept-delete'"
            />
            <!-- <el-button size="mini" type="danger" @click="handleDel" v-has="'dept-delete'">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :title="action == 'create' ? '创建部门' : '编辑部门'"
      v-model="showModal"
    >
      <el-form
        ref="dialogFormRef"
        :model="deptForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="上级部门" prop="parentId">
          <el-cascader
            placeholder="请选择上级部门"
            v-model="deptForm.parentId"
            :props="{ checkStrictly: true, value: '_id', label: 'deptName' }"
            clearable
            :options="deptList"
            :show-all-levels="true"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            placeholder="请输入部门名称"
            v-model="deptForm.deptName"
          ></el-input>
        </el-form-item>
        <el-form-item label="负责人" prop="user">
          <el-select
            placeholder="请选择部门负责人"
            v-model="deptForm.user"
            @change="handleUser"
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.userName"
              :value="`${item.userId}/${item.userName}/${item.userEmail}`"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="负责人邮箱" prop="userEmail">
          <el-input
            placeholder="请输入负责人邮箱"
            v-model="deptForm.userEmail"
            disabled
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button @click="handleSubmit" type="primary">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, nextTick } from 'vue';
import utils from '../utils/utils';
import $api from '../api';
import { ElMessage } from 'element-plus';
import Modal from '../components/Modal.vue';

const queryFormRef = ref();
const dialogFormRef = ref();
const queryForm = reactive({
  deptName: '',
});
const columns = reactive([
  { label: '部门名称', prop: 'deptName' },
  { label: '负责人', prop: 'userName' },
  {
    label: '更新时间',
    prop: 'updateTime',
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
  {
    label: '创建时间',
    prop: 'createTime',
    formatter(row, column, value) {
      return utils.formateDate(new Date(value));
    },
  },
]);
const deptList = ref([]);
const action = ref('create');
const showModal = ref(false);
const deptForm = reactive({
  parentId: [null],
});
const userList = ref([]);
const rules = reactive({
  parentId: [{ required: true, message: '请选择上级部门', trigger: 'change' }],
  deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  user: [{ required: true, message: '请选择部门负责人', trigger: 'change' }],
});

// 部门列表初始化
const getDeptList = async () => {
  let params = { ...queryForm };
  const list = await $api.getDeptList(params);
  deptList.value = list;
};
const getUserList = async () => {
  userList.value = await $api.getAllUserList();
};
// 部门名称选择
const handleUser = (val) => {
  const [userId, userName, userEmail] = val.split('/');
  // 拷贝关联到邮箱
  Object.assign(deptForm, { userId, userName, userEmail });
};
// 表单重置
const handleReset = (form) => {
  form.resetFields();
};
// 表单创建
const handleOpen = () => {
  action.value = 'create';
  showModal.value = true;
};
// 表单编辑
const handleEdit = (row) => {
  action.value = 'edit';
  showModal.value = true;
  nextTick(() => {
    Object.assign(deptForm, row, {
      user: `${row.userId}/${row.userName}/${row.userEmail}`,
    });
  });
};
// 表单删除
const handleDel = async (_id) => {
  action.value = 'delete';
  let params = { _id, action: action.value };
  await $api.deptOperate(params);
  ElMessage.success('删除成功');
  getDeptList();
};
// 表单关闭
const handleClose = () => {
  handleReset(dialogFormRef.value);
  showModal.value = false;
};
// 表单提交
const handleSubmit = () => {
  dialogFormRef.value.validate(async (valid) => {
    if (valid) {
      let params = { ...deptForm, action: action.value };
      delete params.user;
      await $api.deptOperate(params);
      ElMessage.success('操作成功');
      handleClose();
      getDeptList();
    }
  });
};
getDeptList();
getUserList();
</script>
